const express = require('express');
const router = express.Router();
const sql = require('../db/index');  // 确保此路径与您的数据库配置文件匹配

// 获取订单列表
router.get('/orders', async (req, res) => {
  let { page = 1, pageSize = 10 } = req.query;
  page = parseInt(page);
  pageSize = parseInt(pageSize);
  let start = (page - 1) * pageSize;
  try {
    const [totalRows] = await sql.query('SELECT COUNT(*) as count FROM jz_order');
    const total = totalRows[0].count;
    const [rows] = await sql.query('SELECT id as orderNum, order_time as orderTime, total as price, status, customer_id as customId, employee_id as employeeId FROM jz_order LIMIT ?, ?', [start, pageSize]);
    res.send({
      code: 200,
      msg: '获取订单列表成功',
      data: {
        total,
        tableHeader: { orderNum: '订单编号', orderTime: '下单时间', price: '总价', status: '状态', customId: '顾客ID', employeeId: '员工ID' },
        tableData: rows
      }
    });
  } catch (error) {
    res.send({
      code: 500,
      msg: '获取订单列表失败',
      error: error.message
    });
  }
});

// 派送订单
router.post('/orders/dispatch/:id', async (req, res) => {
  const { id } = req.params;
  const { employee_id } = req.body;  // 前端应传入要指派的员工ID
  try {
    const [result] = await sql.query('UPDATE jz_order SET employee_id = ?, status = ? WHERE id = ?', [employee_id, '待接单', id]);
    if (result.affectedRows === 0) {
      return res.status(404).send({ code: 404, msg: '订单不存在或未更新' });
    }
    res.send({ code: 200, msg: '订单派送成功' });
  } catch (error) {
    res.send({ code: 500, msg: '订单派送失败', error: error.message });
  }
});

// 取消订单
router.post('/orders/cancel/:id', async (req, res) => {
  const { id } = req.params;
  try {
    const [result] = await sql.query('UPDATE jz_order SET employee_id = NULL, status = ? WHERE id = ?', ['待派单', id]);
    if (result.affectedRows === 0) {
      return res.status(404).send({ code: 404, msg: '订单不存在或未更新' });
    }
    res.send({ code: 200, msg: '订单取消成功' });
  } catch (error) {
    res.send({ code: 500, msg: '订单取消失败', error: error.message });
  }
});

module.exports = router;
